#!/usr/bin/env node

//静态 + HTTP  API  POST /cmd=xxxx
const cp = require('child_process');
const http = require('http');
const log = console.log;
const fs = require('fs');
const {join} = require('path');


http.createServer((req,res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*');
    log(`${req.method} ${req.url} ${req.headers['user-agent']}`)
    if(req.method === 'GET') {
        file(req, res);
    }else if(req.method === 'POST' && req.url === '/'){
        api(req, res);
    }else {
        res.statusCode = 404;
        res.end('error');
    }
}).listen(3000);

function file(req, res) {

    let file= join(__dirname,req.url);
    if(!fs.existsSync(file)) {
        res.end(`${req.url} not exists!`);
        return;
    }
    fs.createReadStream(file).pipe(res);
}

function api(req, res) {
    let cmd = '';
    req.on('data',chunk => cmd += chunk);
    req.on('end', ()=> {
        cmd = new URLSearchParams(cmd).get('cmd');
        log(cmd);
        cp.exec(cmd, (err, out, errMsg) => {
            if(err) {
                res.statusCode = 500;
                res.end('error:', errMsg);
            }else {
                log({out});
                res.end(JSON.stringify(out.toString()));
            }
        });
    })
}